import React from 'react'
import { Link } from 'react-router-dom'
import { Breadcrumb } from 'antd'
import { HomeOutlined } from '@ant-design/icons'
import cloneDeep from 'clone-deep'
import config from '@/config'
import styles from './index.module.less'

// 额外的带面包屑 页面（非菜单）
const { extraBreadPages } = config

const Bread = ({ location, gState, extraItems = [] }: any) => {
  const { menuList = [] } = gState

  const getPathList = (array: menuItemType[] = []) => {
    const data = cloneDeep(array)
    const pathList: any[] = []

    const forArr = (list: menuItemType[] = []) => {
      list.forEach((_: menuItemType) => {
        const { subMenuList: children = [], url: path, menuName: pathName } = _
        let pathItem = { path, pathName, ableLink: false }
        if (children && children.length > 0) {
          forArr(children)
          // pathList.push(pathItem) // 加入头部一级导航菜单名（注掉则无）
        } else {
          pathList.push({ ...pathItem, ableLink: true })
        }
      })
    }
    forArr(data)

    return pathList
  }

  const pathList = getPathList(menuList).concat(extraBreadPages)
  const pathSnippets = location.pathname.split('/').filter((_: any) => _)
  const defaultBreadcrumbItems = pathSnippets.map((_: any, index: number) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`
    // console.log(url)
    const pathItem = pathList.find((_) =>
      _.path instanceof RegExp ? _.path.test(url) : _.path === url,
    )

    const breadContent = pathItem ? (
      pathItem.ableLink ? (
        <Link to={url}>{pathItem.pathName}</Link>
      ) : (
        pathItem.pathName
      )
    ) : null
    return <Breadcrumb.Item key={String(url)}>{breadContent}</Breadcrumb.Item>
  })

  const breadcrumbItems = [
    <Breadcrumb.Item key="index">
      <Link to="/">
        <HomeOutlined />
      </Link>
    </Breadcrumb.Item>,
  ]
    .concat(defaultBreadcrumbItems)
    .concat(extraItems)

  return (
    <div className={styles['bread_wrap']}>
      <Breadcrumb separator=">">{breadcrumbItems}</Breadcrumb>
    </div>
  )
}

export default Bread
